const fs = require('fs');
const path = require('path');

module.exports = function getEntriesRouter({ baseUrl, srcPath }) {
    const entries = {};
    const routers = {};
    const ROOT_PATH_LEN = path.resolve(baseUrl, srcPath).length + 1;

    function handleDir(dir) {
        if (fs.statSync(dir).isDirectory()) {
            const dirNames = fs.readdirSync(dir).map(item => path.resolve(dir, item));
            dirNames.forEach((item) => {
                const STAT = fs.statSync(item);
                if (STAT.isFile() && /\/View.js$/.test(item)) {
                    const entryKey = item.slice(ROOT_PATH_LEN).split('/').slice(0, -1).join('/');
                    entries[entryKey] = item;

                    const FILE_CONTENT = fs.readFileSync(item, 'utf8');

                    FILE_CONTENT.replace(/\n\s*WPT.allPage\[['"](.+)['"]\]/g, (matchStr, $0) => {
                        routers[$0] = entryKey;
                    });
                } else if (STAT.isDirectory()) {
                    handleDir(item);
                }
            });
        }
    }

    handleDir(srcPath);

    return {
        entries,
        routers
    };
};
